
using System;
using System.Text;
using System.Net;
// Includeing the M2Mqtt Library
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace blue.communication{
    
    public class MqttPublisher{
        public string broker_ip_;
        public int broker_port_=1833; // Default port is 1833
        private MqttClient client_;
        private string client_id_;
        private string topic_;

        public MqttPublisher(string topic, string broker_ip, string client_id){
            broker_ip_ = broker_ip;
            topic_ = topic;
            client_id_ = client_id;
            // Connect to Broker
            client_ = new MqttClient(broker_ip_);
            client_.Connect(client_id_);
        }

        public bool publish(string msg){
            byte[] msg_bytes = Encoding.UTF8.GetBytes(msg);
            return publish(msg_bytes);
        }

        public bool publish(byte[] msg_bytes){
            // publish a bytes on topic with QoS 2
            ushort msg_id = client_.Publish(topic_, msg_bytes
                , MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); 
            return true;
        }
    }
} // end of namespace